package com.badger.spring.boot.security.sms;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

/**
 * 短信登录过滤器
 * @author liqi
 */
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SMS_MOBILE = "phone";

    public static final String CODE = "code";

    public static final String IDENTITY_SMS = "identity_sms";

    public SmsAuthenticationFilter() {
        super(new AntPathRequestMatcher("/auth/login/sms", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        String loginName = request.getParameter(SMS_MOBILE);
        if (StringUtils.isEmpty(loginName)) {
            throw new AuthenticationServiceException("手机号不能为空");
        }
        String code = request.getParameter(CODE);
        if (StringUtils.isEmpty(code)) {
            throw new AuthenticationServiceException("手机验证码不能为空");
        }
        String identity_sms = request.getParameter(IDENTITY_SMS);
        if (StringUtils.isEmpty(identity_sms)) {
            throw new AuthenticationServiceException("身份信息不能为空");
        }
        // 验证短信验证码
        Object attribute = request.getSession().getAttribute(identity_sms);
        if (attribute != null && attribute.toString().equals(code)) {
            SmsAuthenticationToken authRequest = new SmsAuthenticationToken(loginName);
            authRequest.setDetails(super.authenticationDetailsSource.buildDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        throw new AuthenticationServiceException("验证码输入不正确");
    }
}
